﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GCC.APIContainer.Auth.Attributes;
using GCC.APIContainer.Utilities;
using GCC.Container.Abstracts;
using GCC.Container.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.DeviceServer.ApiModels.DeviceParam;
using System.DeviceServer.Models;
namespace System.DeviceServer
{
    [ApiController]
    [Route("[controller]")]
    public class DeviceParamServer : GCCAPIControllerBase
    {
        public DeviceParamServer(AbsGCCContext context) : base(context)
        {
        }

        [HttpGet("devparams/id/{id}")]
        //[GCCAuth(allowOffline: true, roles: new string[] { "admin" })]
        public DataResponse<List<GetDeviceParamsByIDResponse>> GetDeviceParamsByID([FromRoute] long id)
        {
            var dbres = GCCEntrance.DBManager!.LocalDB!.Select<DevParam>()
                .Where(item => item.DevID == id).Count(out var count)
                .ToList();

            return HandleData(dbres.Select(item => new GetDeviceParamsByIDResponse()
            {
                ParamName = item.ParamName,
                Value = item.Value,
            }).ToList(), count);
        }

        [HttpPut("devparams/id/{id}")]
        //[GCCAuth(allowOffline: false, roles: new string[] { "admin" })]
        public DataResponse<bool> UpdateDeviceParams([FromBody] UpdateDeviceParamRequest request, long id)
        {
            if (request is null)
            {
               return IllegalRequest<bool>();
            }
            if(string.IsNullOrWhiteSpace(request.ParamName) || string.IsNullOrWhiteSpace(request.Value))
            {
                return InvalidParameter<bool>();
            }
            var res = GCCEntrance.DBManager!.LocalDB!.Update<DevParam>()
                .Set(a => a.Value, request.Value)
                .Where(a => a.DevID == id && a.ParamName == request.ParamName)
                .ExecuteAffrows() == 1;
            if (res)
            {
                _ = GCCContext.Remove("DevParams"); 
            }
            return HandleData(res);

        }
    }
    
}
